package com.haoyun.common.exception;

import com.haoyun.common.core.BaseException;
import com.haoyun.common.core.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by twg on 2018/2/22.
 * RestFul请求统一异常处理
 */
@Slf4j
@ControllerAdvice(value = "com.haoyun")
public class RestFulHandlerExceptionResolverWrapper extends ResponseEntityExceptionHandler {

    @ResponseBody
    @ExceptionHandler({Exception.class})
    public ResponseEntity handleException(HttpServletRequest request, Throwable ex) {
        log.error("RestFul请求异常：{}", ex);
        HttpStatus status = getStatus(request);
        if(ex instanceof BaseException){
            return new ResponseEntity(Result.buildErrorResult(status.value(), ex.getMessage()), status);
        }
        return new ResponseEntity(Result.buildErrorResult(status.value(), "系统异常！"), status);
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request
                .getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        try {
            return HttpStatus.valueOf(statusCode);
        } catch (Exception ex) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }
}
